package com.moqianfan.mcuassistant.activity

import android.support.v4.view.ViewPager
import android.view.KeyEvent
import android.view.MenuItem
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.limh.base.adapter.FragmentAdapter
import com.limh.base.router.RouterPath
import com.limh.froum.HomeFragment
import com.limh.study.StudyFragment
import com.limh.user.view.MineFragment
import com.moqianfan.mcuassistant.R
import com.moqianfan.mcuassistant.fragment.ToolsFragment
import com.moqianfan.mcuassistant.utils.BottomNavigationViewHelper


@Route(path = RouterPath.AppModule.path_app_main)
class MainActivity : BaseActivity() {

    private val fragments = listOf(HomeFragment(), StudyFragment(), ToolsFragment(), MineFragment())
    private var menuItem: MenuItem? = null

    override fun findView() {
        setContentView(R.layout.activity_main)
    }

    override fun initViews() {
        vpMain.adapter = FragmentAdapter(supportFragmentManager, fragments)
        vpMain.currentItem = 0
        vpMain.offscreenPageLimit = 3

        navMenu.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.item_home -> vpMain.setCurrentItem(0, false)
                R.id.item_learn -> vpMain.setCurrentItem(1, false)
                R.id.item_tools -> vpMain.setCurrentItem(2, false)
                R.id.item_mine -> vpMain.setCurrentItem(3, false)
            }
            return@setOnNavigationItemSelectedListener false
        }
        BottomNavigationViewHelper.disableShiftMode(navMenu)
        vpMain.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                if (menuItem != null) {
                    menuItem?.isChecked = false
                } else {
                    navMenu.menu.getItem(0).isChecked = false
                }
                menuItem = navMenu.menu.getItem(position)
                menuItem?.isChecked = true
            }
        })
    }

    override fun initDatas() {

    }

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(applicationContext, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show()
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                System.exit(0)
            }
        }
        return true
    }
}